package net.wicp.tams.common.io;

import java.io.IOException;
import java.io.InputStream;

import net.wicp.tams.common.apiext.ByteUtil;

/***
 * 读流的一些帮助
 * 
 * @author zhoujunhui
 *
 */
public class InputStreamAssit {

	private final InputStream is;

	public InputStreamAssit(InputStream is) {
		this.is = is;
	}

	public int readInt(int length) throws IOException {
		byte[] bytes = readBytes(length);
		return ByteUtil.readInt(bytes, true);
	}

	public long readLong(int length) throws IOException {
		return ByteUtil.readLong(readBytes(length), true);
	}

	public byte[] readBytes(int length) throws IOException {
		int total = 0;
		final byte[] body = new byte[length];
		while (total < body.length) {
			total += is.read(body, total, body.length - total);
		}
		return body;
	}

	public byte readByte() throws IOException {
		return readBytes(1)[0];
	}

	/**
	 * 读字符
	 * 
	 * @param length
	 *            一定要是偶数
	 * @return 得到的字符
	 * @throws IOException
	 *             读异常
	 */
	public String readStr(int length) throws IOException {
		return new String(readBytes(length - length % 2), "UTF-8");
	}

}
